#include "./includes/mqtt.h"
#include "stdlib.h"
#include <winsock2.h>
#include <windows.h>
#include "stdio.h"
#include <process.h>

#define OS 0

SOCKET sclient;
unsigned char rev[1024] = {0};


u8 socket_connect(char *host, u16 port){
    WORD sockVersion = MAKEWORD(2, 2);
    WSADATA data;
    if (WSAStartup(sockVersion, &data) != 0){
        return false;
    }
    sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sclient == INVALID_SOCKET){
        printf("invalid socket !");
        return false;
    }
    struct sockaddr_in serAddr;
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(port);
    serAddr.sin_addr.S_un.S_addr = inet_addr(host);
    if (connect(sclient, (struct sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR){
        printf("connect error !");
        closesocket(sclient);
        return false;
    } else{
        printf("connect %s:%d success！", host, port);
    }
    return true;
}

void recv_thread(void){
    while (1){
        int ret = recv(sclient, rev, 1024, 0);
        if (ret > 0){
            //printf("\n收到 %d byte 数据，开始解码\n", ret);
            mqtt_decode(rev, ret);
        }
        Sleep(100);
    }
}

void send_data(char *data, u16 len){
    send(sclient, data, len, 0);
}

void on_connect(){
    printf("mqtt 连接成功！\n");
}

void on_message(char *topic, char *msg){
    printf("\n收到来自topic[%s] 的消息\n\t\t=> %s\n", topic, msg);
}

void on_error(char *err){
    printf("mqtt 连接失败: %s！\n", err);
}

void disconnect(){
    printf("mqtt连接断开！\n");
    closesocket(sclient);
    WSACleanup();
    exit(0);
}

void clear(char *buf, u16 size){
    u16 i = 0;
    for (i=0; i< size; i++){
        buf[i] = 0;
    }
}

void cmd_thread(void){
    char topic[255], msg[255];
    while (1){
        clear(topic, 255);
        clear(msg, 255);
        printf("\n请输入topic msg: ");
        scanf("%s %s", &topic, &msg);
        printf("\n发布mqtt消息 topic[%s] msg[%s]\n", topic, msg);
        mqtt_publish(topic, strlen(topic), msg, strlen(msg), 0, 0);
    }
}

void sys_tick(){
    while (1){
        mqtt_sys_tick_s();
        printf(".");
        Sleep(1000);
    }
}


int main(int argc, char* argv[]){
    //构造mqtt所需配置
    MQTT_CONFIG mqttConfig;
    mqttConfig.host = "127.0.0.1";
    mqttConfig.port = 1880;
    // /iot/data/up/20220307331700514301 {"header":"iot.prop.post","body":{"sw1":0,"sw2":1,"sw3":0,"sw4":1}}
    mqttConfig.client_id = "20220307331700514301";
    mqttConfig.username = "698227268354854913";
    mqttConfig.password = "c3bd7d849506b2f8";
    mqttConfig.keep_alive = 10;
    mqttConfig.clean_session = true;
    MQTT_CALLBACK callback;
    callback.on_connect = on_connect;
    callback.on_message = on_message;
    callback.on_error = on_error;
    callback.disconnect = disconnect;
    mqttConfig.callback = callback;

    //设置无缓冲，print调用即可打印
    setvbuf(stdout, NULL, _IONBF, 0);
    //启动新线程，异步接收
    _beginthread(recv_thread, 0,NULL);
   // _beginthread(cmd_thread, 0,NULL);
    _beginthread(sys_tick, 0,NULL);
    //发起连接
    mqtt_connect(&mqttConfig, send_data, socket_connect);

    if(mqtt_subscribe("/iot/data/down/20220307331700514301", 0)){
        printf("订阅topic成功！");
    } else{
        printf("订阅topic失败！");
    }

    int time = 0;
    while (1){
        Sleep(1000);

        /*printf(".");
        if (++time >= 60){
            time = 0;
            printf(" 1min \n");
        }*/
    }
   /* closesocket(sclient);
    WSACleanup();*/
    return 0;
}
